// OptionsState.cpp: implementation of the OptionsState class.
//
//////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdlib.h>

#ifdef FREEGLUT_IS_PRESENT
#  include <GL/freeglut.h>
#else
#  ifdef __APPLE__
#    include <GLUT/glut.h>
#  else
#    include <GL/glut.h>
#  endif
#endif

#include "OptionsState.h"
#include "BackGroundImage.h"
#include "ImageButton.h"
#include "Keyboard.h"
#include "Mouse.h"

#include "tinyxml2/tinyxml2.h"

using namespace tinyxml2;

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

OptionsState::OptionsState()
{
this->oldState = NULL;
this->load("OptionsState.xml");
}

OptionsState::OptionsState(State* oldState)
{
this->oldState = oldState;
this->load("OptionsState.xml");
}

OptionsState::~OptionsState()
{	
delete backgroundImage;
delete backButton;
delete ms;
delete kb;
}

void OptionsState::display(void)
{
backgroundImage->display();
backButton->display();
}

void OptionsState::load(const char* filename)
{	
	XMLDocument doc;
	doc.LoadFile(filename);
	
	XMLElement* guiElement = doc.FirstChildElement( "gui" );
	
	XMLElement* frameElement = guiElement->FirstChildElement( "frame" );
		
	this->backgroundImage = new BackGroundImage(frameElement->Attribute("backgroundImage"));

	XMLElement* backButtonElement = frameElement->FirstChildElement("button");
										  
	backButton = new ImageButton(backButtonElement->Attribute("normalImage"),
								 backButtonElement->Attribute("focusedImage"),
								 backButtonElement->Attribute("clickedImage"),
								 eAlphaKey_RED,
								 0.43f,0.01f,0.15f,0.1f);
	this->kb = new Keyboard();
	this->ms = new Mouse();
								 
	nextState = this;
}

void OptionsState::reset()
{
this->nextState = this;
}

void OptionsState::resize(int w, int h)
{

}

void OptionsState::keyUp(unsigned char key, int x, int y)
{
kb->read(key,GLUT_UP,x,y);
}

void OptionsState::keyDown(unsigned char key, int x, int y)
{
kb->read(key,GLUT_DOWN,x,y);
}

void OptionsState::specialUp(int key, int x, int y)
{
kb->read(key,GLUT_UP,x,y);
}

void OptionsState::specialDown(int key, int x, int y)
{
kb->read(key,GLUT_DOWN,x,y);
}

void OptionsState::motion(int newx, int newy)
{

}

void OptionsState::passive(int newx, int newy)
{
backButton->mouse(-1,-1,newx,newy);
}

void OptionsState::mouse(int button, int state, int mouseX, int mouseY)
{
if(backButton->mouse(button,state,mouseX,mouseY)) this->nextState = this->oldState;
}

State* OptionsState::idle(void)
{
if(kb->isPressed(27)) exit(0);
if(nextState == this) return nextState;
else {State* tmpState = nextState; this->reset(); return tmpState;}
}

